<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Amap;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Attachment;
use app\common\model\City;
use app\common\model\Version;
use fast\Random;
use OSS\OssClient;
use think\captcha\Captcha;
use think\Config;
use think\Hook;
use function EasyWeChat\Kernel\data_get;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'captcha','upload', 'cityList', 'convert2Address', 'nearestCity'];
    protected $noNeedRight = '*';

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /**
     * 加载初始化
     *
     * @ApiParams (name="version", type="string", required=true, description="版本号")
     * @ApiParams (name="lng", type="string", required=true, description="经度")
     * @ApiParams (name="lat", type="string", required=true, description="纬度")
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @ApiParams (name="file", type="file", required=true, description="文件流")
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $config = get_addon_config('alioss');
            $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            //检测删除文件或附件
            $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
                //如果设定为不备份则删除文件和记录 或 强制删除
                if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
                    if ($attachment && !empty($attachment['id'])) {
                        $attachment->delete();
                    }
                    if ($upload) {
                        //文件绝对路径
                        $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
                        @unlink($filePath);
                    }
                }
            };
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
//            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
//
//            $this->success(__('Uploaded successful'), ['url' => cdnurl($attachment->url,true), 'fullurl' => cdnurl($attachment->url, true)]);
            //文件绝对路径
            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

            $url = $attachment->url;

            try {
                $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
                //成功不做任何操作
            } catch (\Exception $e) {
                $checkDeleteFile($attachment, $upload, true);
                \think\Log::write($e->getMessage());
                $this->error("上传失败(1002)");
            }
            $checkDeleteFile($attachment, $upload);

            // 记录云存储记录
            $data = $attachment->toArray();
            unset($data['id']);
            $data['storage'] = 'alioss';
            Attachment::create($data, true);

            $this->success("上传成功", '', ['url' => cdnurl($url,$config['cdnurl']), 'fullurl' => cdnurl($url, $config['cdnurl'])]);
        }

    }

    /**
     * 验证码
     * @ApiParams (name="id", type="string", required=true, description="要生成验证码的标识")
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

    /**
     * 城市列表
     *
     * @ApiMethod (POST)
     */
    public function cityList()
    {
        $cityModel = new City();
        $fields = ['id', 'name', 'standing_initial', 'address', 'lat', 'lng', 'start_num', 'start_price', 'other_price'];
        $citys = $cityModel->where('status', 1)->field($fields)->select();
        $data = [];
        foreach ($citys as $city) {
            if (empty($data[$city['standing_initial']])) {
                $data[$city['standing_initial']] = [
                    'standing_initial' => $city['standing_initial'],
                    'citys' => [],
                ];
            }
            $data[$city['standing_initial']]['citys'][] = $city;
        }
        $this->success(__('Operation completed'), array_values($data));
    }

    /**
     * 经纬度转地址
     *
     * @ApiMethod (POST)
     * @ApiParams (name="lnt", type="string", required=false, description="经度")
     * @ApiParams (name="lat", type="string", required=false, description="纬度")
     */
    public function convert2Address()
    {
        $lnt = $this->request->post('lnt');
        $lat = $this->request->post('lat');
        $data = [];
        if (!empty($lnt) && !empty($lat)) {
            $longitudePattern = '/^-?(?:180(?:\.0+)?|(?:1[0-7]\d|\d{1,2})(?:\.\d+)?)$/';
            $latitudePattern = '/^-?(?:90(?:\.0+)?|[1-8]?\d(?:\.\d+)?)$/';
            if (!preg_match($longitudePattern, $lnt) || !preg_match($latitudePattern, $lat)) {
                $this->error(__('Invalid parameters'));
            }
            $response = Amap::instance()->regeo($lnt, $lat);
            if ($response['status'] == 1 && !empty($response['regeocode']['formatted_address'])) {
                $data['address'] = $response['regeocode']['formatted_address'];
            } else {
                $this->error(__('Address acquisition failed'));
            }
        } else {
            $ip = $this->request->ip();
            $response = Amap::instance()->ip2Address($ip);
            if ($response['status'] == 1) {
                $data['address'] = $response['province'] . $response['city'];
            } else {
                $this->error(__('Address acquisition failed'));
            }

        }
        $this->success(__('Operation completed'), $data);
    }

    /**
     * 最近的城市
     *
     * @ApiMethod (POST)
     * @ApiParams (name="lnt", type="string", required=true, description="经度")
     * @ApiParams (name="lat", type="string", required=true, description="纬度")
     */
    public function nearestCity()
    {
        $lnt = $this->request->post('lnt');
        $lat = $this->request->post('lat');
        if (empty($lnt) || empty($lat)) {
            $this->error(__('Invalid parameters'));
        }
        $longitudePattern = '/^-?(?:180(?:\.0+)?|(?:1[0-7]\d|\d{1,2})(?:\.\d+)?)$/';
        $latitudePattern = '/^-?(?:90(?:\.0+)?|[1-8]?\d(?:\.\d+)?)$/';
        if (!preg_match($longitudePattern, $lnt) || !preg_match($latitudePattern, $lat)) {
            $this->error(__('Invalid parameters'));
        }
        $cityModel = new City();
        $distanceString = '( 6371 * acos (  
                    cos ( radians('.$lat.') )  
                    * cos( radians( lat ) )  
                    * cos( radians( lng ) - radians('.$lnt.') )  
                    + sin ( radians('.$lat.') )  
                    * sin( radians( lat ) )  
                    )  
                ) as distance';
        $fields = ['id', 'name', 'standing_initial', 'address', 'lat', 'lng', 'start_num', 'start_price', 'other_price', $distanceString];
        $data = $cityModel->where('status', 1)->field($fields)->order('distance', 'asc')->find();
        if (!$data) {
            $this->error(__('City acquisition failed'));
        }
        $this->success(__('Operation completed'), $data);
    }
}
